﻿$ErrorState = 2
$ErrorMessage = ""
$Trace = ""
$Value = ""
$Error.Clear()

$virstoNamespace = "root\virtualization\storage"
$virstoDiskSnapshotClass = 'Virsto_VSVDiskSnapshot'
$cloneName = '%CLONENAME%'
$diskId = "%DISKID%"
$cloneId = ""
$cloneDescription = "%DISCRIPTION%"



try {

  $Trace += 'Connecting to Virsto...  \n'
  $diskSnapshot = Get-WmiObject -Namespace $virstoNamespace -Class $virstoDiskSnapshotClass -Filter "ID=$diskId"
  if ($diskSnapshot -eq $null) {
			$ErrorState = 1
			$Trace += 'Virsto Snapshot not exists...  \n'
  }
  else
  {
	   $vdisk1 = gwmi -query "select * from Virsto_VSVDisk where name='$cloneName'" -namespace $virstoNamespace
	   if ($vdisk1 -eq $null)
	   {
		   $Trace += 'Creating Virsto Clone...  \n'

		   $result = $diskSnapshot.Clone($cloneName, $cloneDescription)

		   $vdisk1 = gwmi -query "select * from Virsto_VSVDisk where name='$cloneName'" -namespace $virstoNamespace
		   if ($vdisk1 -eq $null)
		   {
				$ErrorState = 1
				$Trace += 'Virsto Clone not created...  \n'
		   }
		   else
		   {
	   			$Trace += 'Virsto Clone successfull created...  \n'
				$CloneId = $vdisk1.Id
				$ErrorState = 0

		   }
		}
		else
		{
	   			$Trace += 'Virsto Clone already exists...  \n'
				$CloneId = $vdisk1.Id
				$ErrorState = 0

		}

  }

}
catch
{
  $ErrorState = 2
  $ErrorMessage = $error[0].Exception.ToString()
}
Finally
{
  $Trace += 'ErrorState:  ' + $ErrorState + ' \n'
  $Trace += 'ErrorMessage: ' + $ErrorMessage + ' \n'
  $Trace += 'CloneId: ' + $CloneId + ' \n'
}

$Results = @($ErrorState, $ErrorMessage, $Trace, $CloneId) 
Return $Results


